<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, toRaw } from "vue";
import { getDeviceConfigApi, setDeviceConfigApi } from '@/api/configs/deviceConfig';
import { useI18n } from "vue-i18n";
import { DeviceModel } from "@/api/products/device";
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";
import { ElMessageBox, ElMessage } from "element-plus";
import CopyDevices from './CopyDevices.vue';

const emit = defineEmits(['onsubmit']);

const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  deviceNo: {
    type: String,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  },
  forceRefresh: {
    type: Number,
    required: false,
    default: 0
  }
});

// TypeScript接口定义，对应后端结构体
interface AeFFTConfBandItem {
  index: number;  // 频段序号 1-5
  start: number;  // 频段起始
  end: number;    // 频段结束
  enable: number; // 频段使能 1 0
}

interface AeFFTConfItem {
  aeFftEnable: number;                    // FFT 使能 1是0否
  extract: number;                        // 抽取系数
  aeFFTConfigBandItems: AeFFTConfBandItem[]; // 频段信息
  updatetime?: number;
}

const i18n = useI18n();

const current = ref({
  configKey: "aefft", // 固定configKey为aefft
  deviceNo: "",
  productId: 0,
  productKey: "",
  updatedAt: 0,
});

const currentDeviceInfo = ref<DeviceModel>();

// 快捷填入配置
const quickFill = ref({
  startValue: 0,
  endValue: 0
});

// 表单数据初始化
const form = ref<AeFFTConfItem>({
  aeFftEnable: 0,
  extract: 1,
  aeFFTConfigBandItems: [
    { index: 1, start: 0, end: 0, enable: 0 },
    { index: 2, start: 0, end: 0, enable: 0 },
    { index: 3, start: 0, end: 0, enable: 0 },
    { index: 4, start: 0, end: 0, enable: 0 },
    { index: 5, start: 0, end: 0, enable: 0 }
  ]
});

// 复制设备配置
const copyDevices = ref<string[]>([]);

// 监听属性变化，加载配置
watch(
  () => props,
  (newVal) => {
    current.value.updatedAt=0
    current.value.deviceNo = newVal.deviceNo;
    current.value.productId = newVal.params.productId;
    current.value.productKey = newVal.params.productKey;
    setTimeout(async () => {
      await loadConfig();
    },0);
  },
  {
    deep: true, immediate: true
  }
);

// 格式化系统时间
const systemTime = computed(() => {
  if (!current.value.updatedAt || current.value.updatedAt == 0) {
    return "-";
  }
  return formatTimestampToDatetime(current.value.updatedAt);
});

const loading = ref(false);

// 加载配置
const loadConfig = async () => {
  try {
    loading.value = true;
    const res = await getDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
    });
    if (res.data?.configValue) {
      form.value = JSON.parse(res.data?.configValue);
      form.value.updatetime =  res.data?.updatedAt
      // 确保频段配置数组存在且长度为5
      if (!form.value.aeFFTConfigBandItems || form.value.aeFFTConfigBandItems.length !== 5) {
        const newBandItems: AeFFTConfBandItem[] = [];
        for (let i = 1; i <= 5; i++) {
          const existingItem = form.value.aeFFTConfigBandItems?.find(item => item.Index === i);
          if (existingItem) {
            newBandItems.push(existingItem);
          } else {
            newBandItems.push({ index: i, start: 0, end: 0, enable: 0 });
          }
        }
        form.value.aeFFTConfigBandItems = newBandItems;
      }

      // 更新当前时间戳
      if (form.value.updatetime) {
        current.value.updatedAt = form.value.updatetime;
      }
    }
  } finally {
    loading.value = false;
  }
};

// 快捷填入功能实现
const applyQuickFill = () => {
  const start = quickFill.value.startValue;
  const end = quickFill.value.endValue;

  // 验证起始值不大于结束值
  if (start >= end) {
    ElMessage.error(i18n.t('device.aefft.START_MUST_LESS_THAN_END'));
    return;
  }

  // 计算每个频段的间隔
  const totalRange = end - start;
  const interval = totalRange / 5;

  // 填充5个频段，上一个频段的结束等于下一个频段的起始
  for (let i = 0; i < 5; i++) {
    form.value.aeFFTConfigBandItems[i].start = Math.round(start + i * interval);
    form.value.aeFFTConfigBandItems[i].end = Math.round(start + (i + 1) * interval);
    form.value.aeFFTConfigBandItems[i].enable = 1; // 自动启用频段
  }

  ElMessage.success(i18n.t('device.aefft.QUICK_FILL_SUCCESS'));
};

// 验证频段配置
const validateBandConfig = () => {
  const bands = form.value.aeFFTConfigBandItems;

  // 验证每个频段的起始不大于结束
  for (const bandItem of bands) {
    if (bandItem.start > bandItem.end) {
      ElMessage.error(`${i18n.t('device.aefft.BAND_START_MUST_LESS_THAN_END')} ${bandItem.index}`);
      return false;
    }
  }

  // 验证上一个频段的结束不大于下一个频段的起始
  for (let i = 0; i < bands.length - 1; i++) {
    if (bands[i].end > bands[i + 1].start) {
      ElMessage.error(`${i18n.t('device.aefft.PREVIOUS_BAND_END_MUST_LESS_THAN_NEXT_START')} ${i + 1} -> ${i + 2}`);
      return false;
    }
  }

  return true;
};

// 保存配置
const saveConfig = async () => {
  try {
    loading.value = true;

    // 准备请求数据
    const reqData = { ...toRaw(form.value) };

    // 验证频段配置
    if (!validateBandConfig()) {
      throw new Error('Invalid band configuration');
    }

    // 额外验证启用的频段的起始小于结束
    for (const bandItem of reqData.aeFFTConfigBandItems) {
      if (bandItem.enable === 1) {
        if (bandItem.start >= bandItem.end) {
          ElMessage.error(i18n.t('device.aefft.START_MUST_LESS_THAN_END'));
          return;
        }
      }
    }

    await setDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
      configValue: reqData,
      copyDevices: copyDevices.value
    });

    ElMessage.success(i18n.t('buttons.tips.success'));

    // 重新加载配置以更新时间戳
    setTimeout(async ()=>{
      await loadConfig();
    },2000)

  } catch (error) {
    ElMessage.error(error.message);
  } finally {
    loading.value = false;
  }
};

// 带二次确认的保存方法
const handleSaveConfig = async () => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      i18n.t('buttons.tips.confirmSaveConfig') + "?",
      "",
      {
        confirmButtonText: i18n.t('buttons.confirm'),
        cancelButtonText: i18n.t('buttons.cancel'),
        type: 'warning'
      }
    );

    // 用户确认后执行保存操作
    await saveConfig();
  } catch (error) {
    // 用户取消或其他错误，不做任何操作
    console.log('保存已取消');
  }
};

onMounted(() => {
});
</script>

<template>
  <div class="aefft-config">
    <el-form :model="form" class="vertical-form">
      <!-- 设备编号 -->
      <el-form-item :label="i18n.t('device.deviceNo')" prop="deviceNo">
        <el-input v-model="current.deviceNo" disabled style="width: 100%; max-width: 300px;" />
      </el-form-item>

      <!-- FFT 使能 -->
      <el-form-item :label="i18n.t('device.aefft.fftEnable')" prop="aeFftEnable">
        <div style="margin-top: 8px;">
          <el-radio-group v-model="form.aeFftEnable">
            <el-radio :label="1" style="margin-right: 20px;">{{ i18n.t('buttons.yes') }}</el-radio>
            <el-radio :label="0">{{ i18n.t('buttons.no') }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>

      <!-- 抽取系数 -->
      <el-form-item :label="i18n.t('device.aefft.extractCoefficient')" prop="extract">
        <el-input-number v-model="form.extract" :min="1" :step="1" style="min-width: 200px;" />
      </el-form-item>

      <!-- 快捷填入功能 -->
      <el-form-item :label="i18n.t('device.aefft.QUICK_FILL')">
        <div style="display: flex; align-items: center; flex-wrap: wrap;">
          <div style="margin-right: 20px; margin-bottom: 10px;">
            <span style="margin-right: 5px;">{{ i18n.t('device.aefft.START') }}:</span>
            <el-input-number v-model="quickFill.startValue" :min="0" :step="1" style="width: 120px;" />
          </div>
          <div style="margin-right: 20px; margin-bottom: 10px;">
            <span style="margin-right: 5px;">{{ i18n.t('device.aefft.END') }}:</span>
            <el-input-number v-model="quickFill.endValue" :min="0" :step="1" style="width: 120px;" />
          </div>
          <el-button type="primary" @click="applyQuickFill" size="small">
            {{ i18n.t('device.aefft.APPLY') }}
          </el-button>
        </div>
      </el-form-item>

      <!-- 频段配置 -->
      <el-form-item :label="''">
        <div v-for="bandItem in form.aeFFTConfigBandItems" :key="bandItem.index" class="band-item">
          <div style="margin-bottom: 15px; border-bottom: 1px solid #ebeef5; padding-bottom: 15px;">
            <div style="width: 80px; font-weight: bold; margin-bottom: 10px;">
              {{ i18n.t('device.aefft.BAND') }} {{ bandItem.index }}
            </div>

            <div style="margin-bottom: 10px;">
              <el-form-item :label="i18n.t('device.aefft.frequencyBandEnable')" label-width="120px">
                <el-radio-group v-model="bandItem.enable">
                  <el-radio :label="1" style="margin-right: 20px;">{{ i18n.t('buttons.yes') }}</el-radio>
                  <el-radio :label="0">{{ i18n.t('buttons.no') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <div style="margin-bottom: 10px;">
              <el-form-item :label="i18n.t('device.aefft.frequencyBandStart')" label-width="120px">
                <el-input-number v-model="bandItem.start" :min="0" :step="1" style="width: 200px;" />
              </el-form-item>
            </div>

            <div style="margin-bottom: 10px;">
              <el-form-item :label="i18n.t('device.aefft.frequencyBandEnd')" label-width="120px">
                <el-input-number v-model="bandItem.end" :min="0" :step="1" style="width: 200px;" />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form-item>


      <!-- 复制设备配置 -->
      <el-form-item :label="i18n.t('device.copyDevices.title')">
        <CopyDevices
          :device-no="current.deviceNo"
          v-model="copyDevices"
        />
      </el-form-item>

      <!-- 系统时间 -->
      <el-form-item :label="i18n.t('device.aeparam.SYSTEM_TIME')">
        <el-input v-model="systemTime" type="text" disabled style="width: 100%; max-width: 300px;" />
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSaveConfig" style="min-width: 150px;">
          {{ i18n.t('buttons.submit') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.aefft-config {
  padding: 20px;
  overflow-x: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 垂直布局样式 */
.band-item {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.band-item:not(:first-child) {
  margin-top: 20px;
}
</style>
